import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import {
	setToken,
	getToken,
	removeToken
} from '@/utils/localStorage.js';
import {
	Toast
} from 'vant';

Vue.use(VueRouter)

const routes = [{
	path: '/',
	redirect: '/Home'
}, {
	path: '/home',
	name: 'Home',
	component: Home
}, {
	path: '/login',
	name: 'Login',
	component: () => import('@/views/Login.vue')
}, {
	path: '/register',
	name: 'Register',
	component: () => import('@/views/Register.vue')
}, {
	path: '/user',
	name: 'User',
	component: () => import('@/views/User.vue'),
	meta: {
		token: true
	}
}, {
	path: '/user_edit',
	name: 'UserEdit',
	component: () => import('@/views/UserEdit.vue'),
	meta: {
		token: true
	}
}, {
	path: '/article',
	name: 'Article',
	component: () => import('@/views/Article.vue')
}, {
	path: '/user_follow',
	name: 'UserFollow',
	component: () => import('@/views/UserFollow.vue'),
	meta: {
		token: true
	}
}, {
	path: '/user_star',
	name: 'UserStar',
	component: () => import('@/views/UserStar.vue'),
	meta: {
		token: true
	}
}, {
	path: '/user_comment',
	name: 'UserComment',
	component: () => import('@/views/UserComment.vue'),
	meta: {
		token: true
	}
}, {
	path: '/comment/:id',
	name: 'Comment',
	component: () => import('@/views/Comment.vue'),
	meta: {
		token: true
	}
}, {
	path: '/category',
	name: 'Category',
	component: () => import('@/views/Category.vue'),
	meta: {
		token: true
	}
}, {
	path: '/search',
	name: 'Search',
	component: () => import('@/views/Search.vue')
}]

const router = new VueRouter({
	routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
	// 排除路径
	if (!to.meta.token) return next()

	console.log('需要登录访问')
	// 已登录
	if (getToken()) return Toast.success({
		message: '用户已登录',
		onClose: () => next({
			path: '/login'
		})
	});
	// 未登录，不放行
	Toast.fail({
		message: '请先登录！',
		onClose: () => next({
			path: '/login'
		})
	});

})

export default router
